package com.jesper.seckill.execption;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import com.jesper.seckill.entity.vo.response.ResponseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定义全局异常拦截器,未处理的返回异常在此统一处理
 */

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = Exception.class)//拦截所有异常
    public ResponseData<String> handleException(Exception e){
        ResponseData<String> resData;
        String msg = e.getMessage();
        if (StrUtil.isBlank(msg)){
            msg = "服务操作失败";
        }
        if (e instanceof ValidateException){
           //一般的业务校验异常
           if (msg.indexOf("请重新登录") > -1 || msg.indexOf("账号已被冻结") > -1){
               resData = ResponseData.custom(401,msg);
           } else {
               resData = ResponseData.error(msg);
           }
           //记录info级别的日志
            log.info(msg);
        } else {
            //其余的异常作为服务器内部异常，需要处理异常日志信息
            resData = ResponseData.custom(500,msg);
            //记录error级别的日志
            log.error(msg,e);
        }
        return resData;
    }
}
